<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form class="search-form" action="/">
         <van-search
           v-model="searchText"
           show-action
           background="#3296fa"
           placeholder="请输入搜索关键词"
           @search="onSearch"
           @cancel="onCancel"
           @focus="isResultShow=false"
         />
    </form>
    <!-- 搜索栏 -->

    <!-- 搜索结果 -->
    <search-result
    v-if="isResultShow"
    :search-text="searchText"/>
    <!-- 搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
    v-else-if="searchText"
    :search-text="searchText"
    @search="onSearch"/>
    <!-- 联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
    v-else
    :search-histories="searchHistories"
    @search="onSearch"
    @clear-search-history="searchHistories=[]"/>
    <!-- 搜索历史记录 -->

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      isResultShow: false,
      searchText: '',
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
      // 从本地存储中获取数据
    }
  },
  computed: {},
  watch: {
    // 简写
    searchHistories (value) {
      // 同步到本地数据
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }
    // 完整写法可以适配更多的条件
    // searchHistories: {
    //   handler () {

    //   }
    // }
  },
  created () {
  },
  methods: {
    onSearch (val) {
      // console.log(val)
      // 更新文本框内容
      this.searchText = val
      // 存储历史记录
      // 进行判断看历史数据是否重复
      // 利用数组的indexOf()方法找到数据的索引当索引为-1时则表示没有改数据
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  padding-top: 108px;
.van-search__action {
color: #fff;
}
.search-form {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}
}
</style>
